Arrow keys / Space to navigate

Module 12: Automating the Deployment Pipeline

Developing Serverless Solutions on AWS

CI/CD for Serverless

Analogy: Factory assembly line. CI = quality control at each station (automated tests). CD = the conveyor belt delivers the product to the customer automatically. Without it, you're hand-carrying each product.
Continuous IntegrationBuild + Test on every commit Continuous DeliveryAuto-deploy to staging Continuous DeploymentAuto-deploy to production Safe DeploymentCanary + auto-rollback Code flows through the pipeline automatically

Why CI/CD for Serverless?

Without CI/CD: Baking one cake manually each time (error-prone, slow). With CI/CD: Automated bakery line - same quality every time, scales to 1000 cakes.

AWS Developer Tools for CI/CD

SourceCodeCommit / GitHub BuildCodeBuild TestCodeBuild + SAM local DeployCloudFormation / SAM MonitorCloudWatch Alarms CodePipeline orchestrates the entire flow

Also works with: GitHub Actions, GitLab CI, Jenkins, Terraform

AWS SAM Pipeline Features

# Initialize a CI/CD pipeline for your SAM app
sam pipeline init --bootstrap

# Creates:
# - IAM roles for pipeline stages
# - S3 bucket for artifacts
# - Pipeline configuration (CodePipeline or GitHub Actions)
# - Separate configs per environment (dev/staging/prod)

# Deploy pipeline
sam deploy --guided  # or use the generated pipeline config

Key SAM Deployment Features

Safe Deployments with Traffic Shifting

StrategyHow It WorksUse Case
Canary10Percent5Minutes10% traffic to new, wait 5 min, then 100%Quick validation, lower risk
Linear10PercentEvery10MinutesAdd 10% every 10 min until 100%Gradual rollout, steady monitoring
AllAtOnceImmediately shift all trafficDev/test environments only
# SAM template - safe deployment config
MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    AutoPublishAlias: live
    DeploymentPreference:
      Type: Canary10Percent5Minutes
      Alarms:
        - !Ref ErrorAlarm
        - !Ref LatencyAlarm
      Hooks:
        PreTraffic: !Ref PreTrafficValidation
        PostTraffic: !Ref PostTrafficValidation
Canary = food taster. Send a small portion of traffic first. If it gets "sick" (errors), don't serve it to everyone. Roll back automatically.

CI/CD Best Practices

One recipe (SAM template), different ingredient amounts per kitchen (dev=small, prod=large). Same process, different scale via parameters.

Multi-Account Pipeline Architecture

Dev Account Unit tests sam deploy --dev Auto-deploy on commit Staging Account Integration tests Load tests Manual approval gate Prod Account Canary deployment CloudWatch alarms Auto-rollback on error SAM Template (same for all envs)

What's New (2024-2025)

Q1: What does DeploymentPreference: Canary10Percent5Minutes do?

B) 10% traffic for 5 min, then 100%
Canary sends a small portion of traffic to the new version. If alarms stay healthy for 5 minutes, it shifts 100%. If alarms fire, it rolls back automatically.
A: Traffic shifting, not account selection. C: All code deploys, traffic is what shifts. D: No waiting before deploy - traffic shifts immediately to 10%.

Q2: Why use separate AWS accounts per environment?

B) Isolate blast radius + security boundaries
A dev mistake can't break prod. Each account has its own IAM, quotas, and network isolation. Also enables separate billing.
A: Same pricing regardless of account. C: You can request increases in any account. D: Stack limits are per-account but that's not the primary reason.

Q3: What triggers an automatic rollback in a SAM safe deployment?

B) CloudWatch Alarm entering ALARM state
You define alarms (Errors > 0, Latency > threshold) in the DeploymentPreference. If any alarm fires during the canary period, CodeDeploy automatically rolls traffic back to the previous version.
A: Manual approval is a gate, not auto-rollback. C: Build failures prevent deploy, don't roll back. D: Unrelated to deployment.

Q4: What do PreTraffic and PostTraffic hooks do?

B) Run validation Lambdas before/after traffic shift
PreTraffic runs before ANY traffic goes to new version (e.g., check DB migrations). PostTraffic runs after shift completes (e.g., integration tests). Either can fail the deployment and trigger rollback.
A: Concurrency is separate. C: You could do this, but that's not the primary purpose. D: DNS is handled by aliases, not hooks.

Live Demo: SAM Canary Deployment

Step 1: Add safe deployment to SAM template

# template.yaml
MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    Handler: app.handler
    Runtime: python3.12
    AutoPublishAlias: live
    DeploymentPreference:
      Type: Canary10Percent5Minutes
      Alarms:
        - !Ref FunctionErrorAlarm

FunctionErrorAlarm:
  Type: AWS::CloudWatch::Alarm
  Properties:
    MetricName: Errors
    Namespace: AWS/Lambda
    Dimensions:
      - Name: FunctionName
        Value: !Ref MyFunction
    Statistic: Sum
    Period: 60
    EvaluationPeriods: 1
    Threshold: 1
    ComparisonOperator: GreaterThanOrEqualToThreshold

Demo: Deploy & Observe Traffic Shift

# Deploy first version
sam build && sam deploy --guided

# Make a code change (introduce a small update)
# Redeploy - canary begins
sam build && sam deploy

# Watch the canary in real-time:
aws codedeploy get-deployment --deployment-id DEPLOYMENT_ID

# In CloudWatch: watch alias traffic weights shift
# 10% to new → wait 5 min → if healthy → 100% to new

What to Show in Console

ServiceDemonstrate
CodeDeployShow deployment in progress, traffic weight shifting 10% → 100%
LambdaShow alias with weighted routing (V1: 90%, V2: 10%)
CloudWatchShow alarm status during canary period
Rollback testDeploy bad code, watch alarm fire + auto-rollback

Module Summary